package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: ApUserServiceImpl
 * Description:
 * Author: yzh
 * Create 2025/3/18 16:10
 * Version: 1.0
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {
        if(!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword())){
            //用户登录
            log.info("用户登录");
            //1.数据库查询用户
            ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            if(dbUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }

            //2.比对密码是否正确
            String password = dto.getPassword();
            String salt = dbUser.getSalt();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //原来使用的==，我服了
            if(!md5DigestAsHex.equals(dbUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }

            //3.返回data，包括用户和jwt
            Map<String,Object> map = new HashMap<>();
            dbUser.setPassword("");
            dbUser.setSalt("");
            map.put("user",dbUser);

            String token = AppJwtUtil.getToken(dbUser.getId().longValue());
            map.put("token",token);

            return ResponseResult.okResult(map);

        }else {
            //游客登陆
            log.info("游客登陆");
            Map<String,Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
